var chart;
var chartHeight = 0;
$(document).ready(function(){
	$("*").css("cursor","progress");

	$(window).resize(function(){
		$("div").first().css("height", $(window).height() - 130 + "px");
		chartHeight = $(document).height() - 253;
		if ($("select").length) {
			$("select").change();
		}
	});
	$(window).resize();

	// Create the month drop-down list
	openDb() && window.db.readTransaction(function(tx){
		tx.executeSql('SELECT lastupdateSeconds FROM usageHistory ORDER BY lastupdateSeconds ASC LIMIT 1', [], function(tx, results) {
			if (results.rows.length == 1) {
				window.firstMonth = parseFloat(date("n", results.rows.item(0).lastupdateSeconds));
				window.firstYear = parseFloat(date("Y", results.rows.item(0).lastupdateSeconds));
				var monthOffset = 0;
				var monthOptions = '';
				var gatheringMonths = true;
				var selected = '';
				while (gatheringMonths) {
					var monthTime = mktime(0,0,0,window.firstMonth+monthOffset,1,window.firstYear);
					if (date("n Y", monthTime) == date("n Y")) {
						gatheringMonths = false;
						selected = "selected";
					}
					monthOptions += '<option value="'+monthOffset+'" '+selected+'>'+ date("F Y",monthTime) + '</option>\n';
					monthOffset++;
				}
				$("#months").html('<select>'+monthOptions+'</select>');
				$("select").focus().change();
			}
		});
	}, function(e){
		// If database hasn't been created yet, say there's no data yet
		console.log(e);
		$("#months").html('<select><option value="0">'+date("F Y")+'</option></select>');
		$("#chart").html('<div style="text-align:center; font-size:14px"><br />Xnet Usage Monitor does not have any data recorded for '+$('option').text()+' yet.</div');
		$("*").css("cursor","");
	});

	// DEV: Function is for fake data generation below
	/*function rand (min, max) {
		var argc = arguments.length;
		if (argc === 0) {
			min = 0;
			max = 2147483647;
		} else if (argc === 1) {
			throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
		}
		return Math.floor(Math.random() * (max - min + 1)) + min;
	}*/

	// Fetch usage history data
	$("select").live("change", function(){
		$("#chart").html('<div style="text-align:center; font-size:14px"><br />Loading...</div>');
		openDb() && window.db.readTransaction(function(tx){

			// Retrieve data for selected month
			var offset = parseFloat($("select").val());
			var monthStart = mktime(0,0,0,window.firstMonth+offset,1,window.firstYear);
			var monthEnd = mktime(0,-1,0,window.firstMonth+offset+1,1,window.firstYear);

			tx.executeSql('SELECT * FROM usageHistory WHERE lastupdateSeconds >= ? AND lastupdateSeconds < ? ORDER BY lastupdateSeconds ASC',
				[monthStart, monthEnd],
			 	function(tx, results){
				if (results.rows.length) {
					var standardData = [];
					var localData = [];
					var freeData = [];

					var utc = function(seconds) {
						// Offset by 12 hours so that it lines up nicely on the grid,
						// otherwise the notches on the x axis are for dates @ 12pm instead of 12am, which looks a bit odd
						return (seconds * 1000) + (1000 * 60 * 60 * 12);
					};

					// Make make start of month have 0 data, so a line gets drawn?
					standardData[0] = [utc(monthStart), 0];
					localData[0] = [utc(monthStart), 0];
					freeData[0] = [utc(monthStart), 0];

					// DEV: Add single point of fake data
					//standardData[1] = [utc(mktime(23,0,0,date("n"),10)), 98.3];

					// DEV: Generate month's worth of fake data
					/*var fakeGB = 0;
					for (var i = 0; i < 2880; i++) {
						fakeGB += rand(0,10) / 500;
						if (date("j",mktime(0, 0, i * 60 * 15, 9, 1, 2011)).substr(-1) == "0") {
							fakeGB += .04;
						}
						standardData[standardData.length] = [
							utc(mktime(0, 0, i * 60 * 15, 9, 1, 2011)),
							fakeGB
						];
						localData[localData.length] = [
							utc(mktime(0, 0, i * 60 * 15, 9, 1, 2011)),
							fakeGB * .25
						];
					}*/

					for (var x = 0; x < results.rows.length; x++) {
						line = results.rows.item(x);
						standardData[standardData.length] = [
							utc(line.lastupdateSeconds),
							parseFloat(number_format(line.total / 1024, 2))
						];
						localData[localData.length] = [
							utc(line.lastupdateSeconds),
							parseFloat(number_format((line.rxlocal+line.txlocal) / 1024, 2))
						];
						freeData[freeData.length] = [
							utc(line.lastupdateSeconds),
							parseFloat(number_format(line.freedataused / 1024, 2))
						];
					}
					var cap = 0;
					var capText = '';
					if (line.capCustom > 0) {
						cap = line.capCustom;
						capText = 'Custom data cap';
					} else if (line.cap > 0) {
						cap = line.cap;
						capText = 'Data cap';
					}

					// Add standard data and local data to chart
					var series = [
						{
							name: "Standard data",
							data: standardData,
							visible:
								localStorage.popup_standardDataUsed == 1 ||
								localStorage.popup_standardDataLeft == 1 ||
								localStorage.tooltip_standardDataUsed == 1 ||
								localStorage.tooltip_standardDataLeft == 1 ? true : false
						}, {
							name: "Local data",
							data: localData,
							visible: localStorage.popup_localDataUsed == 1 || localStorage.tooltip_freeDataUsed == 1 ? true : false
						}
					];
					var colors = [
						'#008fbf',	// blue
						'#090'		// green
					];

					// Add free data to chart if user's used any
					if (freeData[freeData.length-1][1] != "0.00") {
						series[series.length] = {
							name: "Free data",
							data: freeData,
							visible: localStorage.popup_freeDataUsed == 1 || localStorage.tooltip_freeDataUsed == 1 || localStorage.popup_dataUsed == 1 || localStorage.tooltip_dataUsed == 1 ? true : false
						};
						colors[colors.length] = '#6600cc'; // purple
					}

					// Add cap to chart if user has one
					if (cap > 0) {
						var capGB = parseFloat(number_format(cap / 1024, 2));
						series[series.length] = {
							name: capText,
							data: [
								[
									utc(monthStart),
									capGB
								],
								[
									utc(monthEnd),
									capGB
								]
							]
						};
						colors[colors.length] = 'rgba(0,0,0,.25)'; // gray
					}

					// Create line chart
					// Documentation available @ http://www.highcharts.com/ref/
					window.chart = new Highcharts.Chart({
						legend: {
							margin: 20,
							borderWidth: 0
						},
						chart: {
							renderTo: "chart",
							type: "line",
							zoomType: "xy",
							height: chartHeight,
							events: {
								load: function(){
									$("*").css("cursor","");
									$("#chart").append('<br /><div style="text-align:center; border-top:1px solid rgba(0,0,0,.1); color:rgba(0,0,0,.8)"><br />&nbsp; '+
											'Drag to zoom. &nbsp; Legend items are toggleable. &nbsp; Data points will be recorded when usage info is updated.</div>')
								}
							},
							reflow: false
						},
						title: {
							text: ""
						},
						xAxis: {
							type: "datetime",
							min: utc(monthStart),
							max: utc(monthEnd),
							tickInterval: 1000 * 60 * 60 * 24,
							tickPosition: "inside",
							endOnTick: true,
							labels: {
								formatter: function() {
									return date("jS", (this.value - (1000*60*60*12)) / 1000);
								}
							},
							alternateGridColor: "#fcfcfc"
						},
						yAxis: {
							title: {
								text:""
							},
							min: 0,
							labels: {
								formatter: function() {
									return this.value+" GB";
								}
							},
							gridLineColor: "rgba(0,0,0,.11)",
							allowDecimals: false,
							tickPixelInterval: 40
						},
						series: series,
						colors: colors,
						tooltip: {
							shared: false,
							crosshairs: true,
							backgroundColor: "#fff",
							borderColor: "rgba(0,0,0,.5)",
							borderWidth: 1,
							borderRadius: 4,
							style: {
								padding: "8px"
							},
							shadow: true,
							formatter: function() { // Format the tooltip
								var toReturn = '';
								var datas = '';
								var totalSeries = 0;
								var lastSeriesName = '';
								var color = '';

								var setColor = function(name) {
									switch (name) {
										case "Standard data":
											color = "#008fbf";
											break;
										case "Local data":
											color = "#090";
											break;
										case "Free data":
											color = "#a04de1";
											break;
										case "Data cap":
											color = 'rgba(0,0,0,.75)';
											break;
										case "Custom data cap":
											color = 'rgba(0,0,0,.75)';
											break;
									}
								};

								var formatInfo = function(name, gb) {
									return '<span style="color:'+color+'; font-size:14px; line-height:18px">'+ name +': '+number_format(gb,2) +' GB</span><br />';
								};
								
								var top = '<div style="font-size:3px; line-height:2px; color:white">&nbsp;</div><br />';
								
								toReturn += '<span style="font-size:14px; line-height:18px; color:rgba(0,0,0,.8)">'+date("D, j M @ g:i a", (this.x - (1000*60*60*12)) /1000)+'</span><br />';

								if (!this.points) {
									setColor(this.series.name);
									lastSeriesName = this.series.name;
									datas += formatInfo(this.series.name, this.y);
									totalSeries++;
								} else {
									// This will only get used if the tooltip is shared (leaving this in in case it ever seems more useful again)
									$.each(this.points, function(i, point) {
										setColor(point.series.name);
										totalSeries++;
										lastSeriesName = point.series.name;
										datas += formatInfo(point.series.name, point.y);
									});
								}

								if (totalSeries == 1 && (lastSeriesName == 'Data cap' || lastSeriesName == 'Custom data cap')) {
									toReturn = datas;
								} else {
									toReturn += datas;
								}
								toReturn += '<br />';
								return top+toReturn;
							}
						},
						credits: {
							enabled:false
						},
						plotOptions: {
							series: {
								animation: false,
								shadow: false,
								lineWidth: 1.3,
								marker: {
									radius: 0,
									states: {
										hover: {
											enabled: true,
											radius: 5
										}
									}
								},
								states: {
									hover: {
										lineWidth: 1.3
									}
								}
							}
						}
					});
				} else {
					var val = $("select").val();
					$("#chart").html('<div style="text-align:center; font-size:14px"><br />Xnet Usage Monitor does not have any data recorded for '+$('option[value="'+val+'"]').text()+'.</div>');
					$("*").css("cursor","");
				}
			});
		});
	});
});